﻿using PhoneStoreWeb.Models;
using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace PhoneStoreWeb.Areas.Admin.Controllers
{
    public class AccountController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }

        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null)
            {
                MembershipService = new MembershipService();
            }
            base.Initialize(requestContext);
        }
        
        public ActionResult LogIn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogIn(LogInModel model, string returnUrl)
        {
            if (User.Identity != null && User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Unauthorized", "Account");
            }
            if (!String.IsNullOrEmpty(model.UserName) && !String.IsNullOrEmpty(model.Password) && MembershipService.CheckUserInRole(model.UserName, "Administrator"))
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Product");
                    }
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    }
}